package com.gewu.pm.ui.activity.sales;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.TerminalContactBean;
import com.gewu.pm.http.glide.GlideApp;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.activity.terminal.TerminalAddTwoActivity;
import com.gewu.pm.ui.adapter.sales.TerminalContactAdapter;
import com.gewu.pm.ui.dialog.AddressDialog;
import com.gewu.pm.ui.dialog.TipsTwoDialog;
import com.gewu.pm.utils.TextStarUtils;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventCode;
import com.hjq.widget.view.ClearEditText;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 新增销售线索页面（第一页 - 输入页）
 * type = 0 新增销售线索页面  type = 1 新增终端     新增终端和这个页面的布局是一样的，唯一不同的就是标题和第一个标签，所以默认是线索销售页面，否则是新增终端页面
 */
public final class SalesLeadAddActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener,
        TerminalContactAdapter.OnContactActionListener {

    // 基本信息
    private TextView mLeadNameLabel;
    private ClearEditText mLeadNameEdit;
    private TextView mFacadePhotoLabel;
    private ImageView mFacadePhotoView;
    private ImageView mFacadePhotoDeleteView;
    private String mFacadePhotoPath;

    // 地区
    private TextView mLocationAreaLabel;
    private TextView mLocationAreaValue;
    private TextView mDetailedAddressLabel;
    private ClearEditText mDetailedAddressEdit;
    private TextView mLatLngLabel;
    private TextView mLatLngValue;

    private TextView mContactInfoLabel;
    private TextView mAddContactButton;

    // 联系人列表
    private RecyclerView mContactRecyclerView;
    private TerminalContactAdapter mContactAdapter;
    private List<TerminalContactBean> mContactList = new ArrayList<>();

    // 下一步按钮
    private TextView mNextStepButton;

    private int type = 0;//type = 0 新增销售线索页面  type = 1 新增终端    新增终端和这个页面的布局是一样的，唯一不同的就是标题和第一个标签，所以默认是线索销售页面，否则是新增终端页面

    public static void start(Context context) {
        start(context, 0);
    }

    public static void start(Context context, int type) {
        Intent intent = new Intent(context, SalesLeadAddActivity.class);
        intent.putExtra(IntentKey.TYPE, type);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.sales_lead_add_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 基本信息
        mLeadNameLabel = findViewById(R.id.tv_lead_name_label);
        mLeadNameEdit = findViewById(R.id.et_lead_name);
        mFacadePhotoLabel = findViewById(R.id.tv_facade_photo_label);
        mFacadePhotoView = findViewById(R.id.iv_facade_photo);
        mFacadePhotoDeleteView = findViewById(R.id.iv_facade_photo_delete);

        // 地区
        mLocationAreaLabel = findViewById(R.id.tv_location_area_label);
        mLocationAreaValue = findViewById(R.id.tv_location_area_value);
        mDetailedAddressLabel = findViewById(R.id.tv_detailed_address_label);
        mDetailedAddressEdit = findViewById(R.id.et_detailed_address);
        mLatLngLabel = findViewById(R.id.tv_lat_lng_label);
        mLatLngValue = findViewById(R.id.tv_lat_lng_value);

        // 联系人信息
        mContactInfoLabel = findViewById(R.id.tv_contact_info);
        mContactRecyclerView = findViewById(R.id.rv_contact_list);

        // 初始化联系人列表
        mContactRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mContactAdapter = new TerminalContactAdapter(this);
        mContactAdapter.setOnContactActionListener(this);
        mContactRecyclerView.setAdapter(mContactAdapter);

        // 下一步按钮（使用内部按钮 ID）
        mNextStepButton = findViewById(R.id.tv_bottom_button);

        // 设置必填标记
        TextStarUtils.setRequiredText(mLeadNameLabel, getString(R.string.lead_name));
        TextStarUtils.setRequiredText(mFacadePhotoLabel, getString(R.string.facade_photo));
        TextStarUtils.setRequiredText(mLocationAreaLabel, getString(R.string.location_area));
        TextStarUtils.setRequiredText(mDetailedAddressLabel, getString(R.string.detailed_address));
        TextStarUtils.setRequiredText(mLatLngLabel, getString(R.string.latitude_longitude));
        TextStarUtils.setRequiredText(mContactInfoLabel, getString(R.string.contact_info));

        // 设置门头照点击事件
        mFacadePhotoView.setOnClickListener(v -> {
            ImageSelectActivity.start(this, 1, this);
        });

        // 设置图片删除按钮点击事件
        mFacadePhotoDeleteView.setOnClickListener(v -> deleteFacadePhoto());

        // 设置点击事件
        setOnClickListener(mLocationAreaValue, mLatLngValue, mNextStepButton);
    }

    @Override
    protected void initData() {
        type = getInt(IntentKey.TYPE, 0);
        if (type == 1) {//1是新增终端
            setTitle("新增终端");
            TextStarUtils.setRequiredText(mLeadNameLabel, getString(R.string.terminal_name));
            mLeadNameEdit.setHint("请输入终端名称");
        } else {//新增线索
            setTitle(R.string.add_sales_lead);
            TextStarUtils.setRequiredText(mLeadNameLabel, getString(R.string.lead_name));
            mLeadNameEdit.setHint("请输入线索名称");
        }
        // 初始化数据
    }
    private String mProvince = "浙江省";//省
    private String mCity = "杭州市";//市
    private String mArea = "滨江区";//区
    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mLocationAreaValue) {// 选择所在地区
            new AddressDialog.Builder(this)
                    //.setTitle("选择地区")
                    // 设置默认省份
                    .setProvince(mProvince)
                    // 设置默认城市（必须要先设置默认省份）
                    .setCity(mCity)
                    // 不选择县级区域
                    //.setIgnoreArea()
                    .setListener((dialog, province, city, area) -> {
                        String address = province + city + area;
                        if (!mLocationAreaValue.getText().equals(address)) {
                            mProvince = province;
                            mCity = city;
                            mArea = area;
                            mLocationAreaValue.setText(address);
                        }
                    })
                    .show();
        } else if (view == mLatLngValue) {
            // 获取经纬度
            toast("点击获取经纬度");
            // TODO: 获取经纬度
        } else if (view == mNextStepButton) {
            // 验证必填项
            String leadName = mLeadNameEdit.getText().toString().trim();
//            if (TextUtils.isEmpty(leadName)) {
//                toast("请输入线索名称");
//                return;
//            }

//            if (TextUtils.isEmpty(mFacadePhotoPath)) {
//                toast("请上传门头照");
//                return;
//            }

            String locationArea = mLocationAreaValue.getText().toString().trim();
//            if (TextUtils.isEmpty(locationArea) || locationArea.equals("请选择")) {
//                toast("请选择所在地区");
//                return;
//            }

            String detailedAddress = mDetailedAddressEdit.getText().toString().trim();
//            if (TextUtils.isEmpty(detailedAddress)) {
//                toast("请输入详细地址");
//                return;
//            }

            String latLng = mLatLngValue.getText().toString().trim();

            if (type == 1) {//1是新增终端
                // 跳转到新增终端第二页
                TerminalAddTwoActivity.start(this, leadName, mFacadePhotoPath, locationArea,
                        detailedAddress, latLng, mContactList);
            } else {//新增线索
                SalesLeadAddTwoActivity.start(this, leadName, "", locationArea, detailedAddress, mFacadePhotoPath);
            }

            // 第二页提交成功后会发送 EventBus 事件（EventCode.SALES_LEAD_ADDED）
            // 本页面接收事件后会自动 finish()（见 receiveEvent 方法）
        }
    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            mFacadePhotoPath = images.get(0);
            updateFacadePhoto();
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }

    /**
     * 更新门头照显示
     */
    private void updateFacadePhoto() {
        if (!TextUtils.isEmpty(mFacadePhotoPath) && new File(mFacadePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mFacadePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mFacadePhotoView);
            mFacadePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mFacadePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mFacadePhotoView.setImageResource(R.drawable.add_ic);
            mFacadePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mFacadePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 删除门头照
     */
    @SingleClick
    private void deleteFacadePhoto() {
        mFacadePhotoPath = null;
        updateFacadePhoto();
        toast("已删除门头照");
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;  // 启用 EventBus
    }

    @Override
    protected void receiveEvent(EventBean event) {
        if (event.getCode() == EventCode.SALES_LEAD_ADDED) {
            // 接收新增线索完成事件，结束掉页面
            finish();
        } else if (event.getCode() == EventCode.TERMINAL_CONTACT_ADD) {
            // 接收新增联系人事件
            TerminalContactBean contact = (TerminalContactBean) event.getData();
            addContact(contact);
        } else if (event.getCode() == EventCode.TERMINAL_CONTACT_EDIT) {
            // 接收编辑联系人事件
            TerminalContactBean contact = (TerminalContactBean) event.getData();
            updateContact(contact);
        }
    }

    /**
     * {@link TerminalContactAdapter.OnContactActionListener}
     * 新增联系人
     */
    @Override
    public void onAdd() {
        // type=0表示销售线索，type=1表示终端
        AddContactActivity.start(this, type);
    }

    /**
     * {@link TerminalContactAdapter.OnContactActionListener}
     * 编辑联系人
     */
    @Override
    public void onEdit(TerminalContactBean contact, int position) {
        // type=0表示销售线索，type=1表示终端
        AddContactActivity.startForEdit(this, contact, position, type);
    }

    /**
     * {@link TerminalContactAdapter.OnContactActionListener}
     * 删除联系人
     */
    @Override
    public void onDelete(int position) {
        new TipsTwoDialog.Builder(getContext()).setTitle("您确定要删除联系人吗").setListener(dialog -> {
            if (position >= 0 && position < mContactList.size()) {
                mContactList.remove(position);
                sortContactList();
                mContactAdapter.setData(mContactList);
            }
        }).show();

    }

    /**
     * 添加联系人
     */
    private void addContact(TerminalContactBean contact) {
        if (contact == null) return;

        // 如果是第一条联系人，默认设为主联系人
        if (mContactList.isEmpty()) {
            contact.setPrimary(true);
        } else {
            // 如果设置为主联系人，取消其他主联系人
            if (contact.isPrimary()) {
                for (TerminalContactBean item : mContactList) {
                    item.setPrimary(false);
                }
            }
        }

        mContactList.add(contact);
        sortContactList();
        mContactAdapter.setData(mContactList);
    }

    /**
     * 更新联系人
     */
    private void updateContact(TerminalContactBean contact) {
        if (contact == null) return;

        int index = contact.getIndex();
        if (index >= 0 && index < mContactList.size()) {
            // 如果设置为主联系人，取消其他主联系人
            if (contact.isPrimary()) {
                for (int i = 0; i < mContactList.size(); i++) {
                    if (i != index) {
                        mContactList.get(i).setPrimary(false);
                    }
                }
            }

            mContactList.set(index, contact);
            sortContactList();
            mContactAdapter.setData(mContactList);
        }
    }

    /**
     * 联系人列表排序（主联系人在前）
     */
    private void sortContactList() {
        Collections.sort(mContactList, new Comparator<TerminalContactBean>() {
            @Override
            public int compare(TerminalContactBean o1, TerminalContactBean o2) {
                if (o1.isPrimary() && !o2.isPrimary()) {
                    return -1;
                } else if (!o1.isPrimary() && o2.isPrimary()) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
    }
}
